"use strict";

const Controller = require("egg").Controller;

/**
 * @controller 文章CRUD
 */
class BlogController extends Controller {
  /**
   * @summary 博客分页查询
   * @router post /api/blogIndex
   * @request body BlogIndexQuery 博客首页查询
   * @apikey
   */
  async indexPage() {
    const { ctx } = this;
    const query = ctx.request.body;
    query.pageNum = parseInt(query.pageNum);
    query.pageSize = parseInt(query.pageSize);
    const blogList = await ctx.service.blog.index(query);
    const total = await ctx.model.Blog.count();
    ctx.body = {
      code: 200,
      msg: "获取博客列表",
      data: { total, blogList },
    };
  }

  /**
   * @summary 博客详情
   * @router get /api/blogs/{id}
   * @request path number id 博客Id
   * @apikey
   */
  async show() {
    const { ctx } = this;
    const blogId = ctx.params.id;
    const blog = await ctx.model.Blog.findByPk(blogId);
    ctx.body = {
      code: blog ? 200 : 404,
      msg: "获取博客详情",
      data: { blog },
    };
  }

  /**
   * @summary 创建博客
   * @router post /api/blogs
   * @request body BlogBody 创建博客Body
   * @apikey
   */
  async create() {
    const { ctx } = this;
    const blog = ctx.request.body;
    ctx.body = {
      code: 200,
      msg: "创建博客",
      data: await ctx.model.Blog.create(blog),
    };
  }

  /**
   * @summary 更新博客提交
   * @router put /api/blogs/{id}
   * @request path number id 博客Id
   * @request body BlogBody 更新博客Body
   * @apikey
   */
  async update() {
    const { ctx } = this;
    const res = await ctx.service.blog.update(ctx.request.body, ctx.params.id);
    ctx.body = {
      code: 200,
      msg: "更新博客",
      data: "操作数量:" + res,
    };
  }

  /**
   * @summary 刪除博客
   * @router delete /api/blogs/{id}
   * @request path number id 博客Id
   * @apikey
   */
  async destroy() {
    const { ctx } = this;
    const blogId = ctx.params.id;
    const res = await ctx.service.blog.destroy(blogId);
    ctx.body = {
      code: 200,
      msg: "(软)删除博客",
      data: "操作数量:" + res,
    };
  }
}

module.exports = BlogController;
